package com.kyzh.core.pager.gamedetail

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.res.ColorStateList
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.text.*
import com.gushenge.core.toast
import android.text.method.LinkMovementMethod
import android.text.style.ForegroundColorSpan
import android.text.style.RelativeSizeSpan
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.fragment.app.Fragment
import com.blankj.utilcode.util.RomUtils
import com.bumptech.glide.Glide
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.gushenge.atools.util.AView
import com.gushenge.atools.util.setHeight
import com.gushenge.core.base.Base
import com.gushenge.core.base.activity.BaseActivity
import com.gushenge.core.beans.*
import com.gushenge.core.dao.GlobalKeys
import com.gushenge.core.dao.MMKVConsts
import com.gushenge.core.dao.MMKVConsts.sub
import com.gushenge.core.dao.MMKVConsts.uid
import com.gushenge.core.impls.GameImpl
import com.gushenge.core.impls.UserImpl
import com.gushenge.core.isShangjia
import com.gushenge.core.listeners.ResultListener
import com.gushenge.core.requests.GameRequest
import com.jeremyliao.liveeventbus.LiveEventBus
import com.kyzh.core.R
import com.kyzh.core.activities.BrowserActivity
import com.kyzh.core.activities.GameBackGroundActivity
import com.kyzh.core.pager.weal.gift.GiftOCouponRecordActivity
import com.kyzh.core.activities.H5Activity
import com.kyzh.core.adapters.GameDetailAdapter
import com.kyzh.core.dialog.showInstallDialog
import com.kyzh.core.download.down.DownActivity
import com.kyzh.core.download.down.DownTask
import com.kyzh.core.extension.intentExtras
import com.kyzh.core.extension.isNotNullOrEmpty
import com.kyzh.core.pager.weal.community.CommunityActivity
import com.kyzh.core.pager.login.LoginActivity
import com.kyzh.core.uis.AnimDownloadProgressButton
import com.kyzh.core.utils.*
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.umeng.socialize.ShareAction
import com.umeng.socialize.UMShareListener
import com.umeng.socialize.bean.SHARE_MEDIA
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMWeb
import com.umeng.socialize.shareboard.ShareBoardConfig
import kotlinx.android.synthetic.main.activity_game_detail2.*
import org.jetbrains.anko.dip
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.textColor
import org.jetbrains.anko.toast
import org.litepal.LitePal
import java.math.BigDecimal


class GameDetailActivity1 : BaseActivity() {
    companion object {
        @JvmStatic
        fun start(context: Context, gid: String, type: String? = "") {
            MMKVConsts.gid = gid
            val starter = Intent(context, GameDetailActivity1::class.java)
                .putExtra("gid", gid)
                .putExtra("type", type)
            context.startActivity(starter)
        }
    }

    private var gid: String? = ""
    private val gmType by intentExtras("type", "")
    private var gameInfo: GameTopDetail = GameTopDetail()
    private var sqlList = Game()

    @SuppressLint("RestrictedApi")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_game_detail2)
        AView.setStatusBar(this, true)
        AView.setMargins(toolbar, 0, AView.getStatusBarHeight(this), 0, 0)
        AView.setMargins(topbg, 0, AView.getStatusBarHeight(this) + dip(45), 0, 0)
        ViewUtils.setHeight(appbar, dip(270) + AView.getStatusBarHeight(this))
        initView()
        initData()
    }

    fun initView() {
        gid = intent.getStringExtra("gid")
        if (gmType.isNotNullOrEmpty()) {
            enterTheBackend.visibility = View.VISIBLE
        } else {
            enterTheBackend.visibility = View.GONE
        }
        closeImg.setOnClickListener { finish() }
        titleMore.setOnClickListener {
            val inflater = getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater
            val contentview: View = inflater.inflate(R.layout.pop_game, null)
            val tvShare = contentview.findViewById<TextView>(R.id.tv_share)
            val tvDown = contentview.findViewById<TextView>(R.id.tv_down)
            tvShare.setOnClickListener {
                //分享
                share()
            }
            tvDown.setOnClickListener {
                //跳转下载列表
                startActivity<DownActivity>()
            }

            contentview.isFocusable = true
            contentview.isFocusableInTouchMode = true
            val popupWindow = PopupWindow(
                contentview, ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            popupWindow.apply {
                width = dip(130)
                height = dip(107)
                isOutsideTouchable = true
                showAsDropDown(titleMore)
                setBackgroundDrawable(resources.getDrawable(R.color.red))
            }
        }
        tv_pinglun.setOnClickListener {
            if (startLogin()) {
                GameCommentActivity.start(this, gid!!, null, null, 0, null)
            }
        }
        initTab()

        enterTheBackend.setOnClickListener {
            GameBackGroundActivity.start(this, gid!!)
        }

    }

    override fun onResume() {
        super.onResume()
        checkBottomState()
        getQun()
    }

    fun checkTab(a: Int) {
        viewpager.currentItem = a
    }

    //显示底部下载按钮状态
    fun checkBottomState() {

        if (gameInfo.system_type == "1") {
            if (gameInfo.aurl.isEmpty()) {
                download.isEnabled = false
                download.setProgressBtnBackgroundColor(Color.GRAY)
                download.backgroundTintList = ColorStateList.valueOf(Color.GRAY)
                return
            }
            havepackage = checkBrowser()
            state = if (havepackage) {
                download.setCurrentText("打开")
                true
            } else {
                download.setCurrentText("下载")
                false
            }
        } else {
            download.setCurrentText("打开")
        }
    }

    fun initBottom() {


        kotlin.runCatching {
            sqlList = LitePal.where("aurl = ?", gameInfo.aurl).findFirst(Game::class.java)
        }


        //判断已经存在过
        if (sqlList.isSaved) {
            val packages = packageManager.getInstalledPackages(0)
            var i = 0
            for (packageInfo in packages) {
                if (packageInfo.packageName == sqlList.packageName) {
                    i++
                }
            }
            state = if (i == 0) {
                false
            } else {
                download.setCurrentText("打开")
                true
            }
            val task = DownTask.getTaskByUrl(gameInfo.aurl)

            val checkStatus = DownTask.checkStatus(gameInfo.aurl)

            if (checkStatus == 2) {
                // 是下载的  就开始监听
                LiveEventBus.get<Map<String, Game>>("GAMETASK").observe(this) {

                }
            }
        } else {
            state = false
        }

        checkBottomState()
        download.setOnClickListener {

            // 下载就收藏
            UserImpl.collect(gid!!, 0, object : ResultListener {
                override fun error(error: String) {
                }

                override fun success(a: Any) {
                    shoucang(true)
                    hasColl = true
                    gameInfo.shoucang_id = a.toString()
                }
            })
            //点击清除下APP全局的
//            val game1 = DownTaskBean()
//                .apply { url = gameInfo.aurl
//                    packageName = gameInfo.android_package
//                    state = 0
//                    process = 0f
//                    icon =gameInfo.icon
//                    name = gameInfo.name
//                    size = gameInfo.size
//                }
//            //
//            DownTask.delectLocal(game1)

            //
            var list1 = DownTaskBean()
            kotlin.runCatching {
                list1 = LitePal.where("url = ?", gameInfo.aurl).findFirst(DownTaskBean::class.java)
            }
            if (startLogin()) {
                if (gameInfo.system_type == "2") {
                    startActivity<H5Activity>("gid" to gid, "heng" to gameInfo.is_heng)
                } else if (gameInfo.aurl.isEmpty()) {
                    if (Base.BASEURL.contains("star.94php.com") || Base.BASEURL.contains("demo.94php.com")) {
                        toast("该游戏禁止下载，请联系400-869-9305")
                    } else {
                        toast("当前游戏不支持下载,请联系客服添加游戏包")
                    }
                } else {
//                    if(!gameInfo.aurl.endsWith(".apk")){
//
//                        toast("下载地址配置错误"+gameInfo.aurl)
//                        return@setOnClickListener
//                    }

                    if (state) {
                        if (gameInfo.android_package.isNullOrEmpty()) {
                            if (list1.isSaved) {
                                if (list1.packageName.isNotEmpty()) {
                                    try {
                                        packageManager.getLaunchIntentForPackage(list1.packageName)
                                            ?.let {
                                                it.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                                                list1.save()
                                                startActivity(it)
                                            }
                                    } catch (e: Exception) {
                                        "请安装游戏或重新下载".toast()
                                    }

                                }
                            }
                        } else {
                            try {
                                packageManager.getLaunchIntentForPackage(gameInfo.android_package)
                                    ?.let {
                                        it.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                                        gameInfo.save()
                                        startActivity(it)
                                    }
                            } catch (e: Exception) {
                                "请安装游戏或重新下载".toast()
                            }
                        }

                    } else {
                        if (list1.isSaved) {
                            DownTask.downLoad(list1)
                        } else {
                            val game1 = DownTaskBean()
                                .apply {
                                    url = gameInfo.aurl
                                    packageName = gameInfo.android_package
                                    state = 0
                                    process = 0f
                                    icon = gameInfo.icon
                                    name = gameInfo.name
                                    size = gameInfo.size
                                    gid = this@GameDetailActivity1.gid!!
                                }
                            if (RomUtils.isXiaomi()) {
                                showInstallDialog {
                                    DownTask.downLoad(game1)
                                }
                            } else {
                                DownTask.downLoad(game1)
                            }
                        }

                    }
                }
            }
        }
    }

    var havepackage = false
    var state = false
    private var hasColl: Boolean = false
    fun initShouCang() {
        if (startLogin()) {
            if (hasColl) {
                UserImpl.collectCancel(gameInfo.shoucang_id, 0, object : ResultListener {
                    override fun error(error: String) {
                        toast(error)
                    }

                    override fun success() {
                        shoucang(false)
                        hasColl = false
                    }
                })
            } else {
                gid?.let {
                    UserImpl.collect(it, 0, object : ResultListener {
                        override fun error(error: String) {
                            toast(error)
                        }

                        override fun success(a: Any) {
                            shoucang(true)
                            hasColl = true
                            gameInfo.shoucang_id = a.toString()
                        }
                    })
                }
            }
        }

    }

    /**
     * 保留兩位小鼠
     */
    fun save2(progress: Float): Float {
        var bd = BigDecimal(progress.toString())
        bd = bd.setScale(2, 4);
        return bd.toFloat();
    }

    /**
     * 校验是打开 还是下载
     */
    fun checkBrowser(): Boolean {
        return if (gameInfo.android_package.isNullOrEmpty()) {
            var list = DownTaskBean()
            kotlin.runCatching {
                list = LitePal.where("url = ?", gameInfo.aurl).findFirst(DownTaskBean::class.java)
            }
            if (list.isSaved) {
                try {
                    val info = packageManager.getApplicationInfo(
                        list.packageName, PackageManager.GET_UNINSTALLED_PACKAGES
                    )
                    true
                } catch (e: PackageManager.NameNotFoundException) {
                    false
                }
            } else {
                false
            }
        } else try {
            val info = packageManager.getApplicationInfo(
                gameInfo.android_package, PackageManager.GET_UNINSTALLED_PACKAGES
            )
            true
        } catch (e: PackageManager.NameNotFoundException) {
            false
        }
    }

    private var shequID = ""

    @RequiresApi(Build.VERSION_CODES.N)
    fun initTab() {


        val beans = arrayListOf<Fragment>(

        )


        GameRequest.gameDetailFenLei(gid) {
            var list = arrayListOf<IndexTop>()
            var hasSheQu = false
            this.forEach {
                if (it.status) {


                    when (it.type) {
                        0 -> {
                            beans.add(GameDetailFragment())
                            list.add(it)
                        }

                        1 -> {
                            beans.add(CommentFragment())
                            list.add(it)
                        }

                        2 -> {
                            beans.add(GameServerFragment())
                            list.add(it)
                        }

                        3 -> {
                            beans.add(GameDealFragment())
                            list.add(it)
                        }

                        4 -> {
                            hasSheQu = true
                            shequID = it.id.toString()
                        }
                    }

                }
            }
            shequ.setVisibility(hasSheQu)
            viewpager.adapter = GameDetailAdapter(supportFragmentManager, beans, list)
            tab.setupWithViewPager(viewpager)
            viewpager.currentItem = 0
        }

        shequ.setOnClickListener {
            // 内容不一致  不用共享动画
            CommunityActivity.start(this, shequID)
        }
    }

    fun initTop() {
        gameInfo.apply {
            Glide.with(this@GameDetailActivity1).load(icon).into(img_gameIcon)
            tv_gameName.text = name
            if (system_type == "2") {
                tv_tip.text = "类型: H5游戏 | $type"
            } else {
                tv_tip.text = "大小: ${size}M | $type"
            }

            setSpan(point)
            if (!tuijianzhishu.isNullOrEmpty()) {
                rbStar.rating = tuijianzhishu.toFloat()
            }

            if (servers != null) {
                if (servers?.data != null && servers!!.data.isNotEmpty()) {
                    setSpan1("${servers!!.data[0].create_time} ${servers!!.data[0].server_name}")
                    //            news_title.text = "开服动态："
                } else {
                    setSpan1("${servers?.message}")
                }
            } else {

            }

            news_title.setOnClickListener {
                checkTab(2)
            }

            if (small_coupon.isNullOrEmpty() || max_coupon.isNullOrEmpty() || small_coupon == "null" || max_coupon == "null") {
                tv_quan_detail.text = "领取优惠券"
            } else {
                tv_quan_detail.text = "领取${small_coupon}～${max_coupon}优惠券"
            }
            if (lb_num == "0") {
                tv_gift_num.visibility = View.GONE
            }
            if (coupon_num == "0") {
                tv_quan_tips.visibility = View.GONE
            }
            tv_gift_num.text = lb_num
            tv_quan_tips.text = coupon_num
            if (!biaoqian.isNullOrEmpty()) {
                bq.removeAllViews()
                var i = 0
                biaoqian.forEach { text ->
                    val textView = TextView(this@GameDetailActivity1)
                    textView.setPadding(dip(4), 0, dip(4), 0)
                    textView.gravity = Gravity.CENTER
                    textView.textSize = 12f
                    textView.text = text
                    val lp = LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.WRAP_CONTENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT
                    )
                    lp.setMargins(0, 0, 10, 0)
                    textView.setLayoutParams(lp)
                    when (i) {
                        0 -> {
                            textView.background =
                                resources.getDrawable(R.drawable.bg_border_radius_orange_3dp)
                            textView.textColor = resources.getColor(R.color.orange)
                        }

                        1 -> {
                            textView.background =
                                resources.getDrawable(R.drawable.bg_border_radius_yellow_3dp)
                            textView.textColor = resources.getColor(R.color.yellow)
                        }

                        2 -> {
                            textView.background =
                                resources.getDrawable(R.drawable.bg_border_radius_green_3dp)
                            textView.textColor = resources.getColor(R.color.green_bg)
                        }

                        else -> {
                            textView.background =
                                resources.getDrawable(R.drawable.bg_border_radius_orange_3dp)
                            textView.textColor = resources.getColor(R.color.orange)
                        }
                    }
                    bq.addView(textView)
                    i++
                }
            } else {
                bq.setVisibility(false)
            }
        }
    }

    fun getQun() {

        GameRequest.genGameQun(gid) {
            this?.apply {
                appbar.setHeight(
                    dip(290) + AView.getStatusBarHeight(this@GameDetailActivity1) + dip(
                        45
                    )
                )
                topbg.setHeight(
                    dip(290) + AView.getStatusBarHeight(this@GameDetailActivity1) + dip(
                        45
                    )
                )
                if (!isShangjia) {
                    conQun.setVisibility(true)
                }
                tvName.text = name
                tvJoin.text = if (is_join == "0") {
                    "加入群聊>"
                } else {
                    "查看消息>"
                }
                tvMES.text = new_xiaoxi
                val s = "已有${num}人加入"
                val spannableString1 = SpannableStringBuilder(s)

                spannableString1.setSpan(
                    ForegroundColorSpan(Color.parseColor("#FC944F")),
                    2,
                    num.length + 2,
                    Spannable.SPAN_INCLUSIVE_EXCLUSIVE
                );
                qunTips.text = spannableString1
                conQun.setOnClickListener {
                    if (startLogin()) {
                        startActivity<BrowserActivity>(
                            GlobalKeys.TITLE to name,
                            GlobalKeys.LINK to url
                        )
                    }
                }
            }
        }

    }

    fun initData() {

        // 群聊控制显示隐藏
//        LiveEventBus.get<Boolean>("login").observe(this){
//            getQun()
//        }
        LiveEventBus.get<Map<String, DownTaskBean>>("GAMETASK").observe(this) {
            Log.e("TAG", "initBottom: " + it.size)
            it[gameInfo.aurl]?.apply {
                Log.e("TAG", "initBottom: 接收到了" + this.state + this.process)
                when (this.state) {
                    0 -> download.setProgressText("下载", this.process)
                    1 -> {
                        download.setProgressText("下载中${this.process}%", this.process)
                        download.state = AnimDownloadProgressButton.DOWNLOADING
                    }

                    2 -> download.setProgressText("等待中", this.process)
                    3 -> {
                        download.setProgressText("安装", this.process)
                        download.state = AnimDownloadProgressButton.NORMAL
                    }
                }
            }
        }
        GameImpl.getGameInfoTop(gid) {
            gameInfo = this
            if (zhekou.isNullOrEmpty()) {
                tv_zhekou.setVisibility(false)
            } else {
                if (!zhekou.contains("折")) {
                    tv_zhekou.text = zhekou + "折"
                } else {
                    tv_zhekou.text = zhekou
                }
                tv_zhekou.setVisibility(true)
                if (zhekou.contains("10")) {
                    tv_zhekou.setVisibility(false)
                }
            }
            if (paihang.isNullOrEmpty()) {
                tv_paiming.setVisibility(false)
            } else {
                tv_paiming.setVisibility(true)
                tv_paiming.text = "TOP:$paihang"
            }

            initTop()
            shoucang(shoucang != "0")
            hasColl = shoucang != "0"
            tv_shoucang.setOnClickListener {
                if (startLogin()) {
                    initShouCang()
                }
            }
            //显示底部下载按钮状态
            checkBottomState()
            initBottom()
            conLiBao.setOnClickListener {
                if (startLogin()) {
                    val time1 = time
                    val httpSign = httpSign(uid + time1)
                    val url =
                        Base.BASEURL + "/?ct=app2021&ac=lb_list&uid=$uid&t=$time1&sign=$httpSign&gid=$gid&member_id=$sub"
                    GiftOCouponRecordActivity.start(
                        this@GameDetailActivity1,
                        1,
                        url,
                        gid!!
                    )
                }
            }
            conQuan.setOnClickListener {
                if (startLogin()) {
                    val time1 = time
                    val httpSign = httpSign(uid + time1)
                    val url =
                        Base.BASEURL + "/?ct=app2021&ac=coupon1&uid=$uid&t=$time1&sign=$httpSign&gid=$gid&member_id=$sub"
                    GiftOCouponRecordActivity.start(
                        this@GameDetailActivity1,
                        2,
                        url,
                        gid!!
                    )
                }
            }
        }

    }

    fun shoucang(shoucang: Boolean) {
        if (!shoucang) {
            tv_shoucang.setCompoundDrawablesWithIntrinsicBounds(
                null,
                resources.getDrawable(R.drawable.ic_game_noshoucang),
                null,
                null
            )
        } else {
            tv_shoucang.setCompoundDrawablesWithIntrinsicBounds(
                null,
                resources.getDrawable(R.drawable.ic_game_shoucang),
                null,
                null
            )
        }
    }

    override fun onPause() {
        super.onPause()
        GSYVideoManager.onPause()
    }

    private fun setSpan1(num: String) {
//        登录即同意“用户协议”和“隐私政策”
        val textTag = "开服动态："
        var text1 = "$textTag$num"
        val span = SpannableString(text1)
        span.setSpan(
            ForegroundColorSpan(this.resources.getColor(R.color.font_66)),
            textTag.length,
            text1.length,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        news_title.text = span
    }


    private fun setSpan(num: String) {
//        登录即同意“用户协议”和“隐私政策”
        val textTag = "评分\n"
        var text1 = "$textTag$num"
        val span = SpannableString(text1)
        val relativeSizeSpan = object : RelativeSizeSpan(1.8f) {
            override fun updateDrawState(ds: TextPaint) {
                super.updateDrawState(ds)
                ds.color = resources.getColor(R.color.font_33)
                ds.isFakeBoldText = true;
                ds.textSize = 60f
                ds.isUnderlineText = false
            }

        }
        span.setSpan(
            relativeSizeSpan,
            textTag.length,
            text1.length,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        img_pingfen.text = span
        img_pingfen.setMovementMethod(LinkMovementMethod.getInstance())
    }

    private fun share() {
        if (showShare()) {
            val config = ShareBoardConfig()
            config.setMenuItemBackgroundShape(ShareBoardConfig.BG_SHAPE_CIRCULAR)
            config.setCancelButtonBackground(Color.rgb(240, 244, 246))
            config.setShareboardBackgroundColor(Color.rgb(240, 244, 246))
            config.setIndicatorVisibility(false)
            config.setTitleText("分享游戏")
            val image = UMImage(this, gameInfo.icon)
            val url = gameInfo.fenxiang
            val web = UMWeb(url)
            web.title = gameInfo.name
            web.setThumb(image)
            web.description = gameInfo.summary
            ShareAction(this)
                .withMedia(web)
                .setDisplayList(
                    SHARE_MEDIA.WEIXIN,
                    SHARE_MEDIA.WEIXIN_CIRCLE,
                    SHARE_MEDIA.QQ,
                    SHARE_MEDIA.QZONE
                )
                .setCallback(shareListener)
                .open(config)
        } else {
            val url = gameInfo.fenxiang
            val createQRImage = createQRImage(url)
            val view = LayoutInflater.from(this).inflate(R.layout.dialog_share, null)
            val code = view.findViewById<ImageView>(R.id.img_code)
            val save = view.findViewById<TextView>(R.id.tv_save)
            code.setImageBitmap(createQRImage)
            save.setOnClickListener {
                if (createQRImage != null)
                    saveResource(createQRImage, gameInfo.name) {
                        "保存成功".toast()
                    }
            }
            val bottomSheetDialog = BottomSheetDialog(this)
            bottomSheetDialog.setContentView(view)
            bottomSheetDialog.show()
        }
    }

    override fun onBackPressed() {
        if (GSYVideoManager.isFullState(this)) {
            GSYVideoManager.backFromWindowFull(this)
        } else {
            finish()
        }
    }

    private val shareListener = object : UMShareListener {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        override fun onStart(platform: SHARE_MEDIA) {

        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        override fun onResult(platform: SHARE_MEDIA) {
            toast("分享成功")
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        override fun onError(platform: SHARE_MEDIA, t: Throwable) {
            toast("分享失败")
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        override fun onCancel(platform: SHARE_MEDIA) {
            toast("分享取消")

        }
    }
}
